﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Steamrunner
{
    class LevelManager : DrawableGameComponent
    {
        SpriteBatch spriteBatch = null;
        LevelFile levelFile = null;

        List<short> tiles = new List<short>();
        
        // tile size
        int tileWidth = 0;
        int tileHeight = 0;
        
        // map size
        int mapWidth = 0;
        int mapHeight = 0;

        Texture2D blackSquare = null;

        public LevelManager(Game game, SpriteBatch spriteBatch)
            : base(game)
        {
            this.spriteBatch = spriteBatch;
        }

        public override void Initialize()
        {
            //levelFile = new LevelFile("FILENAME");
            //levelFile.Parse();
            
            //tiles = levelFile.Shorts;

            // initialize tileWidth, tileHeight
            // initialize mapWidth, mapHeight

            base.Initialize();
        }

        protected override void LoadContent()
        {
            // load tiles??
            blackSquare = Game.Content.Load<Texture2D>(@"Images/Tiles/black");
        }

        public override void Draw(GameTime gameTime)
        {
            // ???
            Vector2 position = Vector2.Zero;

            for (int y = 0; y < mapHeight; y++)
            {
                for (int x = 0; x < mapWidth; x++)
                {
                    position = GetTilePosition(x, y);

                    switch (GetTileTypeByTilePos(x, y))
                    {
                        case 0 :
                            // DO NOTHING
                            break;
                        case 1 :
                            spriteBatch.Draw(blackSquare, position, Color.White);
                            break;
                    }
                }
            }

            base.Draw(gameTime);
        }

        private Vector2 GetTilePosition(int x, int y)
        {
            Vector2 temp;

            temp.X = x * tileWidth;
            temp.Y = y * tileHeight;

            return temp;
        }

        private short GetTileTypeByTilePos(int x, int y)
        {
            return tiles[y * mapWidth + x];
        }

        public short GetTileTypeByScreenPos(Vector2 position)
        {
            int tileX = 0;
            int tileY = 0;
            ScreenToTile((int)position.X, (int)position.Y, ref tileX, ref tileY);
            return GetTileTypeByTilePos(tileX, tileY);
        }

        private void ScreenToTile(int screenX, int screenY, ref int tileX, ref int tileY)
        {
            tileX = screenX / tileWidth;
            tileY = screenY / tileHeight;
        }

        public short GetTileTypeByIndex(int index)
        {
            return tiles[index];
        }
    }
}
